<?php
/**
 * Description: 获取直播课堂播放地址
 * User: devforma
 * Date: 15/6/6
 * Time: 23:22
 */

require LIB_DIR . '/LiveCourse.class.php';
require LIB_DIR . '/EEOAPI.php';

class ClassEntryUrl implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb, $uddb;

        if (validateUser($queryArgs) !== 1 || empty($queryArgs['course_id']) || !is_numeric($queryArgs['course_id'])
            || empty($queryArgs['is_open'])) {
            return genOutput(1000);
        }

        if ($queryArgs['is_open'] === 'true') { //公开课
            $room = LiveCourse::getOpenClassInfo($queryArgs['course_id']);

        } else { //直播课
            if (empty($queryArgs['class_id']))
                return genOutput(1000);

            $room = LiveCourse::getPurchasedClassInfo($queryArgs['course_id'], $queryArgs['class_id'], $queryArgs['user_id']);
            $room->live_platform = $room->platform;
        }

        if (empty($room)) { //课堂信息无效
            return genOutput(1001);
        }

        $isMobile = false;
        if ($queryArgs['terminal_type'] == 'iOS_phone' || $queryArgs['terminal_type'] == 'android_phone'
            || $queryArgs['terminal_type'] == 'mobile_web' || $queryArgs['terminal_type'] == 'hybrid') {
            $isMobile = true;
        }

        $nickname = $this->getUserNickname($queryArgs['user_id']); //获取用户昵称

        //获取播放地址
        if ($room->live_platform === '多贝云' || $room->live_platform === '多贝') {
            if (empty($room->room_id)) {
                return genOutput(1001);
            }

            $url = $this->getDuobeiClassUrl($room->room_id, $queryArgs['user_id'], $nickname, $room->live_platform === '多贝云', $isMobile);
        } elseif ($room->live_platform === '欢拓云') {
            $mtRoomid = $cmsdb->getVar('SELECT t.maituo_room_id FROM `data_teacher` AS t, `data_live_class` AS c WHERE t.id=c.lector_id AND c.id=:cid',
                array(':cid' => $room->id));

            if (empty($mtRoomid)) {
                return genOutput(1001);
            }

            $url = $this->getHuantuoClassUrl($room->id, $mtRoomid, $queryArgs['user_id'], $nickname, strtotime($room->end_time) < time());
        } elseif ($room->live_platform === 'eeo') {

            $eeoCourseId = $cmsdb->getVar('SELECT `eeo_course_id` FROM `data_live_course` WHERE `id`=:id', array(':id' => $queryArgs['course_id']));
            $eeoClassId = $cmsdb->getVar('SELECT `eeo_class_id` FROM `data_live_class` WHERE `id`=:id', array(':id' => $queryArgs['class_id']));
            $phone = $uddb->getVar('SELECT `phone` FROM `user_auth_info` WHERE `ID`=:uid', array(':uid' => $queryArgs['user_id']));

            if ($eeoClassId && $eeoCourseId && $phone) {
                $eeo = new EEO();
                $url = $eeo->getClassEntryUrl($eeoCourseId, $eeoClassId, $phone);
            }

        } else {
            return genOutput(1001);
        }

        if (!empty($url)) {

            //用户进课堂记录
            $this->enterClass($queryArgs['user_id'], $queryArgs['course_id'], $room->id, $room->lector_id, $queryArgs['is_open'] === 'true');

            //公开课访问记录
            if ($queryArgs['is_open'] === 'true') {
                LiveCourse::logEnter($queryArgs['user_id'], $queryArgs['course_id'], $queryArgs['terminal_type'], $room->start_time);
            }

            return genOutput(1, array('url' => $url));
        }

        return genOutput(1001);
    }

    /**
     * 用户观看记录
     *
     * @param $userId
     * @param $courseId
     * @param $classId
     * @param $lectorId
     * @param $isOpen
     */
    private function enterClass($userId, $courseId, $classId, $lectorId, $isOpen) {
        global $cmsdb;

        $exists = $cmsdb->getVar('SELECT `id` FROM `data_liveclass_grade` WHERE `user_id`=:uid AND `class_id`=:cid LIMIT 1',
            array(':uid' => $userId, ':cid' => $classId));

        if (empty($exists)) {
            $cmsdb->insert('data_liveclass_grade', array(
                'course_id' => $courseId,
                'class_id' => $classId,
                'lector_id' => $lectorId,
                'user_id' => $userId,
                'grade_score' => 0,
                'is_openclass' => $isOpen,
                'enter_time' => date('Y-m-d H:i:s'),
                'comment' => ''
            ));
        }
    }


    /**
     * 获取欢拓云播放地址
     *
     * @param $classId
     * @param $mtRoomId
     * @param $userId
     * @param $nickname
     * @param bool $isEnded
     * @return array
     */
    private function getHuantuoClassUrl($classId, $mtRoomId, $userId, $nickname, $isEnded = false) {
        global $cmsdb;
        $mt = new MTCloud();

        if (!$isEnded) { //未结束
            $result = $mt->userAccess($userId, $nickname, MTCloud::ROLE_USER, $mtRoomId);

        } else { //回放
            $liveRecord = $cmsdb->getRow('SELECT `liveid`, `status` FROM `data_htlive_class` WHERE `class_id`=:cid',
                array(':cid' => $classId));

            if (empty($liveRecord) || $liveRecord->status !== 'playback') {
                return '';
            }

            $result = $mt->userAccessPlayback($userId, $nickname, MTCloud::ROLE_USER, $liveRecord->liveid);
        }

        if (is_array($result) && $result['code'] == 0) {
            return $result['data']['shortUrl'];
        } else {
            return '';
        }
    }

    /**
     * 校验用户是否可见课程
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @param bool $isOpenCourse 是否为公开课
     * @return bool
     */
    private function isCourseAvailable($userId, $courseId, $isOpenCourse) {
        global $cmsdb;

        if ($isOpenCourse) {
            $available = $cmsdb->getVar('SELECT `is_available` FROM `gray_user_open_course` WHERE `user_id`=:uid
            AND `course_id`=:cid', array(':uid' => $userId, ':cid' => $courseId));

        } else {
            $available = $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid
            AND `product_id`=:cid AND `product_type`="zhiboke"', array(
                ':uid' => $userId,
                ':cid' => $courseId
            ));
        }

        return empty($available) ? false : true;
    }


    /**
     * 获取用户昵称
     * @param int $userId 用户id
     * @return string
     */
    function getUserNickname($userId) {
        global $uddb;

        $nickname = $uddb->getVar('SELECT `nickname` FROM `user_social_info` WHERE `user_id`=:user_id',
                array(':user_id' => $userId));

        if (empty($nickname))
            return 'student'.$userId;

        return $nickname . $this->getSuffix();
    }

    /**
     * 获取昵称后缀
     * @return string
     */
    function getSuffix() {
        $suffix = '';
        if ($_GET['terminal_type'] === 'pc_web') {
            $suffix = '-yaoguo.cn网站';
        } elseif ($_GET['terminal_type'] === 'mobile_web') {
            $suffix = '-yaoguo.cn手机站';
        } elseif ($_GET['app_type'] === 'dailyplan') {
            $suffix = '-上岸计划App';
        } elseif ($_GET['app_type'] === 'dailylearn') {
            $suffix = '-每日一题App';
        } elseif ($_GET['app_type'] === 'quizbank') {
            $suffix = '-天天模考App';
        }

        return $suffix;
    }

    /**
     * 获取课堂进入地址
     * @param string $roomId 房间id
     * @param int $userId 用户id
     * @param string $nickname 用户昵称
     * @param bool $isH5 是否支持H5
     * @param bool $isMobile 是否为移动端
     * @return string
     */
    private function getDuobeiClassUrl($roomId, $userId, $nickname, $isH5, $isMobile = false) {
        if ($isH5) {
            $api = "http://api.duobeiyun.com/api/v3/room/enter?";
        } else {
            $api = "http://api.jiangzuotong.com/api/v2/room/enter?";
        }

        $params = array(
            'nickname' => trim($nickname),
            'partner' => '20140807101355',
            'roomId' => $roomId,
            'timestamp' => time() * 1000,
            'uid' => $userId,
            'deviceType' => $isMobile ? 2 : 1,
            'userRole' => 2 //2为学生上课地址
        );


        /*****************************************************
         * 生成签名
         */
        ksort($params);

        $paramStr = '';

        foreach($params as $key => $value) {
            $paramStr .= (strval($key).'='.strval($value).'&');
        }
        $sign = md5(rtrim($paramStr, '&').'771f3c17303c49f6a8dc3e3ffbf41990');


        /*****************************************************
         * 构造播放地址
         */
        $paramStr = '';

        foreach($params as $key => $value) {
            $paramStr .= (strval($key).'='.urlencode(strval($value)).'&');
        }

        $paramStr .= ('sign='.$sign);
        return $api.$paramStr;
    }
}